<!-- API端点测试区域 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card feature-card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-cogs text-primary me-2"></i>
                    API端点测试
                </h5>
                <p class="text-muted">选择要测试的API端点，查看请求和响应</p>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">选择API端点</label>
                            <select class="form-select" id="api-endpoint">
                                <option value="">选择一个端点...</option>
                                <optgroup label="健康检查">
                                    <option value="GET:/health">GET /health - 健康检查</option>
                                </optgroup>
                                <optgroup label="认证API">
                                    <option value="GET:/api/v1/auth/config">GET /api/v1/auth/config - 认证配置</option>
                                    <option value="POST:/api/v1/auth/register">POST /api/v1/auth/register - 用户注册</option>
                                    <option value="POST:/api/v1/auth/login">POST /api/v1/auth/login - 用户登录</option>
                                    <option value="GET:/api/v1/auth/me">GET /api/v1/auth/me - 获取用户信息 [需认证]</option>
                                </optgroup>
                                <optgroup label="用户管理">
                                    <option value="GET:/api/v1/users">GET /api/v1/users - 用户列表</option>
                                    <option value="POST:/api/v1/users">POST /api/v1/users - 创建用户</option>
                                    <option value="GET:/api/v1/users/1">GET /api/v1/users/1 - 获取用户详情</option>
                                </optgroup>
                                <optgroup label="文章管理">
                                    <option value="GET:/api/v1/posts">GET /api/v1/posts - 文章列表</option>
                                    <option value="POST:/api/v1/posts">POST /api/v1/posts - 创建文章 [需认证]</option>
                                </optgroup>
                                <optgroup label="支付功能">
                                    <option value="GET:/api/v1/payments/config">GET /api/v1/payments/config - 支付配置</option>
                                </optgroup>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">认证Token <small class="text-muted">(可选)</small></label>
                            <input type="text" class="form-control" id="auth-token" placeholder="Bearer token...">
                            <small class="text-muted">从认证测试页面获取token</small>
                        </div>
                    </div>
                </div>
                
                <div class="text-center">
                    <button class="btn btn-primary btn-custom" onclick="testApiEndpoint()">
                        <i class="fas fa-paper-plane me-1"></i>发送请求
                    </button>
                    <button class="btn btn-secondary btn-custom" onclick="clearResults()">
                        <i class="fas fa-eraser me-1"></i>清空结果
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 请求体配置 -->
<div class="row mb-4" id="request-body-section" style="display: none;">
    <div class="col-12">
        <div class="card feature-card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-code text-info me-2"></i>
                    请求体配置
                </h5>
                <p class="text-muted">为POST/PUT请求配置JSON请求体</p>
                
                <div class="mb-3">
                    <label class="form-label">请求体 (JSON格式)</label>
                    <textarea class="form-control" id="request-body" rows="8" placeholder='{ "key": "value" }'></textarea>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <button class="btn btn-outline-info w-100" onclick="loadSampleData()">
                            <i class="fas fa-magic me-1"></i>加载示例数据
                        </button>
                    </div>
                    <div class="col-md-6">
                        <button class="btn btn-outline-warning w-100" onclick="validateJson()">
                            <i class="fas fa-check me-1"></i>验证JSON格式
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 快速测试按钮 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card feature-card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-bolt text-warning me-2"></i>
                    快速测试
                </h5>
                <p class="text-muted">一键测试常用API功能</p>
                
                <div class="row">
                    <div class="col-md-3 mb-2">
                        <button class="btn btn-outline-success w-100 btn-custom" onclick="quickTest('health')">
                            <i class="fas fa-heartbeat me-1"></i>健康检查
                        </button>
                    </div>
                    <div class="col-md-3 mb-2">
                        <button class="btn btn-outline-info w-100 btn-custom" onclick="quickTest('auth-config')">
                            <i class="fas fa-shield-alt me-1"></i>认证配置
                        </button>
                    </div>
                    <div class="col-md-3 mb-2">
                        <button class="btn btn-outline-primary w-100 btn-custom" onclick="quickTest('users')">
                            <i class="fas fa-users me-1"></i>用户列表
                        </button>
                    </div>
                    <div class="col-md-3 mb-2">
                        <button class="btn btn-outline-secondary w-100 btn-custom" onclick="quickTest('posts')">
                            <i class="fas fa-file-alt me-1"></i>文章列表
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 测试结果显示 -->
<div class="row">
    <div class="col-md-6">
        <div class="card feature-card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-upload text-primary me-2"></i>
                    请求信息
                </h5>
                <div id="request-info" class="code-block">
                    等待请求...
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card feature-card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-download text-success me-2"></i>
                    响应结果
                </h5>
                <div id="response-info" class="code-block">
                    等待响应...
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 示例数据模板
const sampleData = {
    'POST:/api/v1/auth/register': {
        "username": "testuser",
        "email": "test@example.com",
        "password": "password123",
        "firstName": "Test",
        "lastName": "User"
    },
    'POST:/api/v1/auth/login': {
        "email": "test@example.com",
        "password": "password123"
    },
    'POST:/api/v1/users': {
        "username": "newuser",
        "email": "newuser@example.com",
        "password": "password123",
        "firstName": "New",
        "lastName": "User"
    },
    'POST:/api/v1/posts': {
        "title": "测试文章标题",
        "content": "这是一篇测试文章的内容，用于演示API功能。",
        "summary": "测试文章摘要",
        "authorId": 1
    }
};

// 监听端点选择变化
document.getElementById('api-endpoint').addEventListener('change', function() {
    const value = this.value;
    const requestBodySection = document.getElementById('request-body-section');
    
    if (value.startsWith('POST:') || value.startsWith('PUT:')) {
        requestBodySection.style.display = 'block';
        loadSampleData();
    } else {
        requestBodySection.style.display = 'none';
    }
});

// 加载示例数据
function loadSampleData() {
    const endpoint = document.getElementById('api-endpoint').value;
    const requestBodyTextarea = document.getElementById('request-body');
    
    if (sampleData[endpoint]) {
        requestBodyTextarea.value = JSON.stringify(sampleData[endpoint], null, 2);
    } else {
        requestBodyTextarea.value = '{\n  \n}';
    }
}

// 验证JSON格式
function validateJson() {
    const requestBody = document.getElementById('request-body').value;
    
    try {
        JSON.parse(requestBody);
        showAlert('✅ JSON格式正确', 'success');
    } catch (error) {
        showAlert('❌ JSON格式错误: ' + error.message, 'danger');
    }
}

// 测试API端点
async function testApiEndpoint() {
    const endpointSelect = document.getElementById('api-endpoint');
    const authToken = document.getElementById('auth-token').value;
    const requestBody = document.getElementById('request-body').value;
    
    if (!endpointSelect.value) {
        showAlert('请选择一个API端点', 'warning');
        return;
    }
    
    const [method, path] = endpointSelect.value.split(':');
    const url = path.startsWith('/api/v1/') ? path : `/api/v1${path}`;
    
    // 构建请求配置
    const requestConfig = {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        }
    };
    
    // 添加认证头
    if (authToken) {
        requestConfig.headers['Authorization'] = authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`;
    }
    
    // 添加请求体
    if ((method === 'POST' || method === 'PUT') && requestBody) {
        try {
            JSON.parse(requestBody);
            requestConfig.body = requestBody;
        } catch (error) {
            showAlert('请求体JSON格式错误: ' + error.message, 'danger');
            return;
        }
    }
    
    // 显示请求信息
    showRequestInfo(method, url, requestConfig);
    
    try {
        showAlert('🔄 发送请求中...', 'info');
        
        const response = await fetch(url, requestConfig);
        const responseData = await response.text();
        
        let parsedData;
        try {
            parsedData = JSON.parse(responseData);
        } catch {
            parsedData = responseData;
        }
        
        // 显示响应信息
        showResponseInfo(response, parsedData);
        
        if (response.ok) {
            showAlert('✅ 请求成功', 'success');
        } else {
            showAlert(`❌ 请求失败: ${response.status} ${response.statusText}`, 'danger');
        }
    } catch (error) {
        showAlert('💥 请求出错: ' + error.message, 'danger');
        showResponseInfo(null, { error: error.message });
    }
}

// 显示请求信息
function showRequestInfo(method, url, config) {
    const requestInfo = document.getElementById('request-info');
    let info = `${method} ${url}\n\n`;
    info += '请求头:\n';
    for (const [key, value] of Object.entries(config.headers)) {
        info += `${key}: ${value}\n`;
    }
    
    if (config.body) {
        info += '\n请求体:\n';
        try {
            const formatted = JSON.stringify(JSON.parse(config.body), null, 2);
            info += formatted;
        } catch {
            info += config.body;
        }
    }
    
    requestInfo.textContent = info;
}

// 显示响应信息
function showResponseInfo(response, data) {
    const responseInfo = document.getElementById('response-info');
    let info = '';
    
    if (response) {
        info += `状态: ${response.status} ${response.statusText}\n`;
        info += `Content-Type: ${response.headers.get('content-type') || 'N/A'}\n\n`;
    }
    
    info += '响应体:\n';
    if (typeof data === 'object') {
        info += JSON.stringify(data, null, 2);
    } else {
        info += data;
    }
    
    responseInfo.textContent = info;
}

// 快速测试
async function quickTest(type) {
    const tests = {
        'health': { method: 'GET', url: '/health' },
        'auth-config': { method: 'GET', url: '/api/v1/auth/config' },
        'users': { method: 'GET', url: '/api/v1/users' },
        'posts': { method: 'GET', url: '/api/v1/posts' }
    };
    
    const test = tests[type];
    if (!test) return;
    
    // 设置端点选择器
    document.getElementById('api-endpoint').value = `${test.method}:${test.url}`;
    
    // 执行测试
    await testApiEndpoint();
}

// 清空结果
function clearResults() {
    document.getElementById('request-info').textContent = '等待请求...';
    document.getElementById('response-info').textContent = '等待响应...';
    document.getElementById('request-body').value = '';
    document.getElementById('auth-token').value = '';
    document.getElementById('api-endpoint').value = '';
    document.getElementById('request-body-section').style.display = 'none';
}

// 显示提示信息
function showAlert(message, type) {
    // 创建或更新提示元素
    let alertEl = document.getElementById('api-alert');
    if (!alertEl) {
        alertEl = document.createElement('div');
        alertEl.id = 'api-alert';
        alertEl.className = 'alert alert-dismissible fade show';
        alertEl.style.position = 'fixed';
        alertEl.style.top = '20px';
        alertEl.style.right = '20px';
        alertEl.style.zIndex = '9999';
        alertEl.style.minWidth = '300px';
        document.body.appendChild(alertEl);
    }
    
    alertEl.className = `alert alert-${type} alert-dismissible fade show`;
    alertEl.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    // 自动隐藏
    setTimeout(() => {
        if (alertEl && alertEl.parentNode) {
            alertEl.remove();
        }
    }, 5000);
}

// 从localStorage加载token
document.addEventListener('DOMContentLoaded', function() {
    const savedToken = localStorage.getItem('access_token');
    if (savedToken) {
        document.getElementById('auth-token').value = savedToken;
    }
});
</script> 